package demo15;

import java.util.*;

public class IteratorDemo {
    public static void main(String[] args) {
        // 创建一个List对象，这里使用ArrayList实现
        List<String> booksList = new ArrayList<>();
        booksList.add("1984");
        booksList.add("To Kill a Mockingbird");
        booksList.add("The Great Gatsby");

        // 创建一个Set对象，这里使用HashSet实现
        Set<String> booksSet = new HashSet<>();
        booksSet.add("1984");
        booksSet.add("To Kill a Mockingbird");
        booksSet.add("The Great Gatsby");

        // 使用Iterator遍历List
        System.out.println("Iterating through the List:");
        Iterator<String> listIterator = booksList.iterator();
        while (listIterator.hasNext()) {
            String book = listIterator.next();
            System.out.println(book);
            // 示例：删除元素
            if (book.equals("To Kill a Mockingbird")) {
                listIterator.remove();
            }
        }

        // 打印List中的所有元素，验证删除操作
        System.out.println("List after removal: " + booksList);

        // 使用Iterator遍历Set
        System.out.println("Iterating through the Set:");
        Iterator<String> setIterator = booksSet.iterator();
        while (setIterator.hasNext()) {
            String book = setIterator.next();
            System.out.println(book);
            // 示例：删除元素
            if (book.equals("The Great Gatsby")) {
                setIterator.remove();
            }
        }

        // 打印Set中的所有元素，验证删除操作
        System.out.println("Set after removal: " + booksSet);
    }
}
